package com.example.moviepro.controller;


import com.example.moviepro.entity.Movie;
import com.example.moviepro.service.FileStoreService;
import com.example.moviepro.service.MovieService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;


@RestController
//@Validated
@RequestMapping("/movie")
public class MovieController {
    @Autowired
    private MovieService movieService;

    @Autowired
    private FileStoreService fileStoreService;



    //添加电影：http://localhost:8080/movie/addmovie
    @PostMapping("/addmovie")
    public ResponseEntity<?> addMovie(@Valid @RequestBody Movie movie,
                                      BindingResult result) {
        if (result.hasErrors()) {
            // 收集所有的错误信息
            List<String> errorMessages = result.getAllErrors().stream()
                    .map(error -> error.getDefaultMessage())
                    .collect(Collectors.toList());
            // 返回包含所有错误信息的响应
            return ResponseEntity.badRequest().body(errorMessages);
        }
        if(movieService.findMovie(movie) != null) {
            return ResponseEntity.badRequest().body("影片已存在");
        }
        movieService.addMovie(movie);
        int id=movieService.findMovieId(movie);
        movie.setId(id);
        return ResponseEntity.ok(movie);
    }


    // 根据 ID 删除电影:http://localhost:8080/movie/deletemovie/{id}
    @DeleteMapping("/deletemovie/{id}")
    public ResponseEntity<Void> deleteMovie(@PathVariable int id) {
        Movie movie=movieService.findMovieById(id);
        if (movie != null) {
            movieService.deleteMovie(id);
            return ResponseEntity.ok().build();
        } else {
            //找不到电影
            return ResponseEntity.notFound().build();
        }
    }

    // 获取所有电影:http://localhost:8080/movie/getAllMovies
    @GetMapping("/getAllMovies")
    public ResponseEntity<List<Movie>> getAllMovies() {
        List<Movie> movies = movieService.getAllMovies();
        return ResponseEntity.ok(movies);
    }


    // 根据 ID 获取电影:http://localhost:8080/movie/getMovieById/{id}
    @GetMapping("/getMovieById/{id}")
    public ResponseEntity<Movie> getMovieById(@PathVariable int id) {
        Movie movie = movieService.findMovieById(id);
        if (movie != null) {
            return ResponseEntity.ok(movie);
        } else {
            return ResponseEntity.notFound().build();
        }
    }




    // 上传电影海报:http://localhost:8080/movie/uploadPoster/{id}
    @PostMapping("/uploadPoster/{id}")
    public ResponseEntity<String> uploadPoster(@RequestParam("file") MultipartFile file,
                                               @PathVariable int id) {
        try {
            // 存储文件并获取文件名
            String fileName = fileStoreService.storeFile(file);
            // 获取电影实体并更新海报 URL
            Movie movie = movieService.findMovieById(id);
            if (movie != null) {
                String posterUrl = "uploads/" + fileName;
                movie.setPosterUrl(posterUrl);
                movieService.updatePosterUrl(posterUrl,movie);
                // 返回海报的下载 URL
                return ResponseEntity.ok(posterUrl);
            } else {
                // 如果电影不存在，返回 404
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            // 处理文件存储相关异常
            return ResponseEntity.internalServerError().body("上传海报失败:"
                    + e.getMessage());
        }
    }




    // 下载电影海报:http://localhost:8080/movie/posters/{id}
    @GetMapping("/posters/{id}")
    public ResponseEntity<?> downloadPoster(@PathVariable int id) {
        try {
            // 构建文件路径
            String filename=movieService.findfilenameByid(id);
            Path filePath = Paths.get(filename);
            System.out.println(filePath);
            Resource resource = new UrlResource(filePath.toUri());
            // 检查资源是否存在且可读
            if (resource.exists() || resource.isReadable()) {
                String contentType = Files.probeContentType(filePath);
                // 返回资源和相应的内容类型
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_TYPE, contentType)
                        .body(resource);
            } else {
                // 如果文件不存在，返回 404
                return ResponseEntity.notFound().build();
            }
        } catch (IOException e) {
            // 处理文件读取相关异常
            return ResponseEntity.internalServerError().body("无法下载文件:"
                    + e.getMessage());
        }
    }
}
